#include "PhysicEntityInstance.h"
#include "PhysicManager.h"

PhysicEntityInstance::PhysicEntityInstance()
{

}

PhysicEntityInstance::PhysicEntityInstance(const PhysicEntityInstance&)
{

}

PhysicEntityInstance PhysicEntityInstance::operator=(PhysicEntityInstance const&)
{
	return PhysicEntityInstance();
}

PhysicEntityInstance::~PhysicEntityInstance()
{

}

bool PhysicEntityInstance::Initialize(PhysicShape* pPhysicShape, bool pIsStatic, XMFLOAT3 pPosition, XMFLOAT4 pOrientation, void* entityPointer)
{
	mPhysicShape = pPhysicShape;
	mIsStatic = pIsStatic;

	btTransform trans;
	trans.setIdentity();      
	trans.setOrigin(btVector3(pPosition.x,pPosition.y,pPosition.z));

	btQuaternion q(pOrientation.x, pOrientation.y, pOrientation.z,pOrientation.w);
	trans.setRotation(q);

	btDefaultMotionState* motionState =  new btDefaultMotionState(trans);
	btVector3 localInertia(0,0,0);

	btScalar mass = 0;
	if( !mIsStatic )
	{
		mass = 1;
		mPhysicShape->CalculateLocalInertia(mass,localInertia);
		mPhysicShape->getShape()->setMargin(0.04);
	}

	btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass,motionState,mPhysicShape->getShape(),localInertia);
	mRigidBody = new btRigidBody(rigidBodyCI);
	mRigidBody->setFriction(0.5f);
	mRigidBody->setUserPointer(entityPointer);
	PhysicManager::Instance()->addRigidBody(mRigidBody);

	return true;
}

XMFLOAT4X4 PhysicEntityInstance::GetTransform()
{
	return ConvertMatrix( mRigidBody->getWorldTransform() );
}

void PhysicEntityInstance::ApplyForce(XMFLOAT3 pForce, XMFLOAT3 pPosition)
{
	mRigidBody->applyCentralImpulse(btVector3(pForce.x,pForce.y,pForce.z));//, btVector3(pPosition.x,pPosition.y,pPosition.z));
}
